﻿using System;
using System.Collections.Generic;
using System.IO;
using Nett;

namespace M2Server
{
    public class VarGlobalConfig
    {
        private readonly TomlTable _tableConfig;
        private const string sConfigName = "global.toml";

        public VarGlobalConfig()
        {
            if (!File.Exists(sConfigName))
            {
                Console.WriteLine($"配置文件{sConfigName}不存在.");
                return;
            }
            var input = new StreamReader(sConfigName);
            _tableConfig = Toml.ReadString(input.ReadToEnd());
        }

        /// <summary>
        /// 加载游戏变量配置
        /// </summary>
        internal void Load()
        {
            for (int i = M2Share.g_Config.GlobalVal.GetLowerBound(0); i <= M2Share.g_Config.GlobalVal.GetUpperBound(0); i++)
            {
                M2Share.g_Config.GlobalVal[i] = GetConfig<int>("Integer", "GlobalVal" + i, M2Share.g_Config.GlobalVal[i]);
            }
            for (int i = M2Share.g_Config.GlobalAVal.GetLowerBound(0); i <= M2Share.g_Config.GlobalAVal.GetUpperBound(0); i++)
            {
                M2Share.g_Config.GlobalAVal[i] = GetConfig<string>("string", "GlobalStrVal" + i, "");
            }
        }

        private T GetConfig<T>(string nodeName, string keyName, object defaultValue)
        {
            if (!_tableConfig.ContainsKey(nodeName))
            {
                return (T)Convert.ChangeType(defaultValue, typeof(T));
            }
            var node = _tableConfig.Get<Dictionary<string, Object>>(nodeName);
            var localVal = default(T);
            var valuesData = node[keyName];
            localVal = (T)Convert.ChangeType(valuesData, typeof(T));
            return localVal;
        }

    }
}
